package com.yuan.util.file;

import java.io.*;

/**
 * Explain:     []
 * Date:        [2017/7/6 08:43]
 * Coder:       [YouYuan]
 * Version:     [1.0]
 */
public class WriteText {

    /**
     * Write text.
     *
     * @param tarFile the tar file
     * @param text    the text
     * @throws IOException the io exception
     */
    public static void writeText(File tarFile, String text) throws IOException {
        Writer writer = getWriter(tarFile);
        writer.write(text);
        writer.flush();
        writer.close();
    }

    /**
     * Write text line.
     *
     * @param tarFile the tar file
     * @param text    the text
     * @throws IOException the io exception
     */
    public static void writeTextLine(File tarFile, String text) throws IOException {
        BufferedWriter writer = getWriter(tarFile);
        writer.write(text);
        writer.newLine();
        writer.flush();
        writer.close();
    }

    /**
     * Gets writer.
     *
     * @param tarFile the tar file
     * @return the writer
     * @throws IOException the io exception
     */
    public static BufferedWriter getWriter(File tarFile) throws IOException {
        FileWriter fileWriter = null;
        if (tarFile == null) {
            return null;
        }
        if (!tarFile.exists()) {
            tarFile.mkdirs();
            tarFile.delete();
            tarFile.createNewFile();
        }
        fileWriter = new FileWriter(tarFile, true);
        BufferedWriter writer = new BufferedWriter(fileWriter);
        return writer;
    }

    /**
     * 按照指定编码将字符串写入文件
     * @param file
     * @param content
     * @param encoding
     * @throws Exception
     */
    public static void writeString(File file, String content, String encoding) throws Exception {
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(file), encoding);
        osw.write(content);
        osw.close();
    }
}
